package com.base.hong.ui.main

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import coil.load
import coil.transform.RoundedCornersTransformation
import com.base.hong.databinding.FragmentHomeBinding
import com.base.hong.ext.dp
import com.base.hong.model.BannerEntity
import com.base.hong.ui.WebViewActivity
import com.base.hong.ui.base.BaseVMFragment
import com.base.hong.ui.main.viewmodel.HomeViewModel
import com.base.hong.utils.HUtils
import com.gyf.immersionbar.ImmersionBar
import com.htt.base_library.util.startActivity
import com.stx.xhb.androidx.entity.BaseBannerInfo


/**
 * @ClassName HomeFragment
 * @Description 首页
 * @Author Hong
 * @Date 2022/2/21 18:46
 * @Version 1.0
 */
class HomeFragment : BaseVMFragment<HomeViewModel, FragmentHomeBinding>(),
    View.OnClickListener {

    override fun initView(view: View, savedInstanceState: Bundle?) {
        super.initView(view, savedInstanceState)
        ImmersionBar.with(this)
            .statusBarView(mViewBinding.toolbarLine)
            .statusBarDarkFont(true, 0.2f)
            .init()
        setBannerView()
    }

    override fun initData() {
        super.initData()
        viewModel.bannerData.observe(this) {
            mViewBinding.banners.setBannerData(it.toMutableList())
        }
    }

    private fun setBannerView() {
        mViewBinding.banners.setIsClipChildrenMode(true)
        //代码设置框架占位图，也可在布局中设置
        mViewBinding.banners.loadImage { _, model, bannerView, _ ->
            (bannerView as? ImageView)?.let {
                if (model is BaseBannerInfo) {
                    it.scaleType = ImageView.ScaleType.CENTER_CROP
                    it.load(model.xBannerUrl as String) {
                        transformations(
                            RoundedCornersTransformation(
                                topLeft = 5.dp.toFloat(),
                                topRight = 5.dp.toFloat(),
                                bottomLeft = 5.dp.toFloat(),
                                bottomRight = 5.dp.toFloat()
                            )
                        )
                    }

                }
            }
        }
        mViewBinding.banners.setOnItemClickListener { banner, model, view, position ->
            var entity = model as BannerEntity
            if (!TextUtils.isEmpty(entity.url)) {
                startActivity<WebViewActivity>("url" to entity.url)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mViewBinding.banners.startAutoPlay()
        loadData()
    }

    override fun onPause() {
        super.onPause()
        mViewBinding.banners.stopAutoPlay()
    }

    override fun loadData() {
        super.loadData()
        viewModel.getBannerInfo()
    }

    override fun onClick(v: View?) {
    }


}